package ro.one.gaeql.impl;

import java.util.ArrayList;
import java.util.List;

import ro.one.gaeql.model.Operator;

import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilter;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;

public class DatastoreQueryBuilder {
	private String entityName;
	private List<FilterPredicate> filterPredicates = new ArrayList<FilterPredicate>();
	
	public DatastoreQueryBuilder(String entityName) {
		this.entityName = entityName;
	}
	
	public void addCondition(String propertyName, Operator operator, Object expectedValue) {
		FilterPredicate fp = new FilterPredicate(propertyName, this.getFilterOperator(operator), expectedValue);
		filterPredicates.add(fp);
	}
	
	private FilterOperator getFilterOperator(Operator operator) {
		if(operator == Operator.Equals) {
			return FilterOperator.EQUAL;
		} else if(operator == Operator.GreaterThan) {
			return FilterOperator.GREATER_THAN;
		} else if(operator == Operator.GreaterThanOrEqual) {
			return FilterOperator.GREATER_THAN_OR_EQUAL;
		} else if(operator == Operator.LessThan) {
			return FilterOperator.LESS_THAN;
		} else if(operator == Operator.LessThanOrEqual) {
			return FilterOperator.LESS_THAN_OR_EQUAL;
		} else {
			return null;
		}
	}

	public Query createQuery() {
		Query q = new Query(this.entityName);

		if(this.filterPredicates.size() > 0) {
			Filter f;
			if(this.filterPredicates.size() == 1) {
				f = filterPredicates.get(0);
			} else {
				List<Filter> filters = new ArrayList<Query.Filter>(this.filterPredicates);
				f = new CompositeFilter(CompositeFilterOperator.AND, filters);
			}
			q.setFilter(f);
		}
		
		return q;
	}
}
